/**
 * 转换时间
 * @param {Object} date
 */
function updatedata(date) {
	var newTime = new Date(date);
	var myYear = newTime.getYear();
	var mymonth = newTime.getMonth() + 1;
	myYear += (myYear < 2000) ? 1900 : 0;
	return (myYear + "-" + mymonth + "-" + newTime.getDate() + " " + newTime.getHours() + ":" + newTime.getMinutes() + ":" + newTime.getSeconds());
}

/**
 * 初始化handlebars
 */
window.onload = function() {
	handlebars();
}

// 产生一个随机数
function getUid() {
	return Math.floor(Math.random() * 100000000 + 10000000).toString();
}

// 获取地址栏传参
function getQueryString(param) {
	var name, value;
	var str = location.href; // 取得整个地址栏
	
	var num = str.indexOf("?")
	str = str.substr(num + 1); // 取得所有参数 stringvar.substr(start [, length ]
	var arr = str.split("&"); // 各个参数放到数组里
	
	for (var i = 0; i < arr.length; i++) {
		num = arr[i].indexOf("=");
		if (num > 0) {
			name = arr[i].substring(0, num);
			value = arr[i].substr(num + 1);
			this[name] = value;
			if (name == param) {
				return decodeURI(value);
			}
		}
	}
	return decodeURI(param);
}

//转换小数点保留两位
function changeTwoDecimal_f(x)    
   {
       if (isNaN(x))    
       {    
           //alert('function:changeTwoDecimal->parameter error');    
           //return false;    
           return '0.00';//如果不是数字的话返回0.00  
       }    
       var f_x = Math.round(eval(x)*100)/100;   
       var s_x = f_x.toString();    
       var pos_decimal = s_x.indexOf('.');    
       if (pos_decimal < 0)    
       {    
           pos_decimal = s_x.length;    
           s_x += '.';    
       }    
       while (s_x.length <= pos_decimal + 2)    
       {    
           s_x += '0';    
       }    
       return s_x;    
   } 

// 获取当前地址栏的本页地址
function getRedirectUrl() {
	var str = location.href; // 取得整个地址栏
	var urls = str.split("/");
	return urls[urls.length - 1];
}

// 初始化Handlebars
function handlebars() {

	// 复杂逻辑判断
	Handlebars.registerHelper('expression', function() {
		var exps = [];
		try {
			// 最后一个参数作为展示内容，也就是平时的options。不作为逻辑表达式部分
			var judge = "==,!=,>,>=,<,<=,||,&&,+,-,*,/,null,'',gt,lt,gt=,lt=";
			var arg_len = arguments.length;
			var len = arg_len - 1;
			for (var j = 0; j < len; j++) {

				var parameter = arguments[j];

				if (judge.indexOf(parameter) < 0 || parameter.length <= 0) {

					if (typeof parameter == "string" || parameter.length <= 0) {
						parameter = '"' + parameter + '"';
					}

				}

				exps.push(parameter);
			}
			console.log(exps.join(' '));
			var result = eval(exps.join(' ').replace("gt", ">").replace("lt", "<"));
			if (result) {
				return arguments[len].fn(this);
			} else {
				return arguments[len].inverse(this);
			}
		} catch (e) {
			throw new Error('Handlerbars ');
		}
	});

	
	// 线上交易状态
	Handlebars.registerHelper('typeHtml', function(type,
		options) {
		switch (type) {
			case 0:
				return "交易关闭";
				break;
			case 1:
				return "取消";
				break;
			case 10:
				return "待付款";
				break;
			case 20:
				return "待发货";
				break;
			case 30:
				return "待收货";
				break;
			case 40:
				return "已收货";
				break;
			case 50:
				return "交易完成";
				break;
			default:
				return "暂无";
				break;
		}
		
	});
	
	
	// 线下交易状态
	Handlebars.registerHelper('typeHtml2', function(type,
		options) {
		switch (type) {
			case 0:
				return "交易关闭";
				break;
			case 10:
				return "等待付款";
				break;
			case 20:
				return "交易成功";
				break;
			case 30:
				return "交易完成";
				break;
			default:
				return "暂无";
				break;
		}
		
	});
	
	// 是否自提
	Handlebars.registerHelper('typeHtml3', function(type,
		options) {
		switch (type) {
			case 1:
				return "是";
				break;
			case 0:
				return "否";
				break;
			default:
				return "暂无";
				break;
		}
		
	});
	
	// 是否退货
	Handlebars.registerHelper('typeHtml4', function(type,
		options) {
		switch (type) {
			case 1:
				return "(退)";
				break;
			default:
				return "";
				break;
		}
		
	});
	

	// 处理判断符
	Handlebars
		.registerHelper(
			'compare',
			function(left, operator, right, options) {
				if (arguments.length < 3) {
					throw new Error(
						'Handlerbars Helper "compare" 需要3位参数');
				}
				var operators = {
					'==': function(l, r) {
						return l == r;
					},
					'===': function(l, r) {
						return l === r;
					},
					'!=': function(l, r) {
						return l != r;
					},
					'!==': function(l, r) {
						return l !== r;
					},
					'lt': function(l, r) {
						return l < r;
					},
					'gt': function(l, r) {
						return l > r;
					},
					'lt=': function(l, r) {
						return l <= r;
					},
					'gt=': function(l, r) {
						return l >= r;
					},
					'typeof': function(l, r) {
						return typeof l == r;
					}
				};

				if (!operators[operator]) {
					throw new Error(
						'Handlerbars Helper "compare" 参数中没有比较符');
				}

				var result = operators[operator](
					left, right);

				if (result) {
					return options.fn(this);
				} else {
					return options.inverse(this);
				}
			});

	// 处理运数转换符
	Handlebars
		.registerHelper(
			'dataframe',
			function(left, operator, right, options) {
				if (arguments.length < 3) {
					throw new Error(
						'Handlerbars Helper "compare" 需要3位参数');
				}
				var operators = {
					'-': function(l, r) {
						return l - r;
					},
					'+': function(l, r) {
						return l + r;
					},
				};

				if (!operators[operator]) {
					throw new Error(
						'Handlerbars Helper "compare" 参数中没有操作符');
				}

				var result = operators[operator](
					left, right);

				return result;
			});

	Handlebars
		.registerHelper(
			'list',
			function(totalPages, pageNumber,
				options) {
				var out = '';
				// "中间段页码"开始页码数
				var startSegmentPageNumber = pageNumber - parseInt(Math
					.floor((5 - 1) / 2));
				// "中间段页码"结束页码数
				var endSegmentPageNumber = pageNumber + parseInt(Math
					.ceil((5 - 1) / 2));
				// 开始第一页页码
				var firstPageNumber = 1;
				// 结束最后一页页码
				var lastPageNumber = totalPages;

				// 如果中间段开始页码小于1，赋值为1
				if (startSegmentPageNumber < 1) {
					startSegmentPageNumber = 1;
				}
				// 如果中间段结束页码大于总页数，赋值为总页数
				if (endSegmentPageNumber > totalPages) {
					endSegmentPageNumber = totalPages;
				}

				// "中间段页码"变量名称
				var segment = new Array();
				// 装入中间段页码，
				for (var i = startSegmentPageNumber; i <= endSegmentPageNumber; i++) {
					segment.push(i);
				}
				// 遍历中间段页码数组
				$.each(
						segment,
						function(index,
							itme) {
							// 如果中间段页码数组中的第一个页码大于开始第一页加一
							if (index == 0 && this > firstPageNumber + 1) {
								out += '<i class="act">...</i>';
							}
							// 如果中间段页码数组中的值“不等于”当前页码则显示为可点击的按钮
							if (this != pageNumber) {
								out += '<a class="last iconfont"  href="javascript:init(' + this + ')">' + this + '</a>';
							} else {
								out += '<i class="act">' + this + '</i>';
							}
							// 如果中间段页码数组中的最后一个页码小于最后一页页码加一
							if (index == segment.length && this < lastPageNumber - 1) {
								out += '<i class="act">...</i>';
							}

						});
				out += ' 跳转到第<select id="select" name="pageNumber" onchange="gotoSelectedPage();">';
				for (var i = 1; i <= totalPages; i++) {
					if (pageNumber == i) {
						out += '<option value="' + i + '" selected="selected">' + i + '</option>';
					} else {
						out += ' <option value="' + i + '">' + i + '</option>';
					}
				}
				return out += '</select>页';
			});

	// 图片所在目录
	Handlebars
		.registerHelper(
			'imgURL',
			function(imgUrl, options) {
				return setting.ip + imgUrl;
			});

	// 图片所在目录
	Handlebars
		.registerHelper(
			'thumbnailURL',
			function(options) {
				return setting.thumbnailURL;
			});

	// 转化时间
	Handlebars
		.registerHelper('formatDate', function(date, options) {
			var newTime = new Date(date);
			var myYear = newTime.getYear();
			var mymonth = newTime.getMonth() + 1;
			myYear += (myYear < 2000) ? 1900 : 0;
			return (myYear + "-" + mymonth + "-" + newTime.getDate() + " " + newTime.getHours() + ":" + newTime.getMinutes() + ":" + newTime.getSeconds());
		});
	
	//
	//价格格式化
	Handlebars.registerHelper('formatPrice', function(price,options) {
		if(price != ""){
			return price/100;
		}else{
			return "";
		}
	});
	
	//速乐购2.0快递方式
	Handlebars.registerHelper('formatExpressType', function(expressType,options) {
		if(expressType == "self-reliance"){
			return "自提";
		}else if(expressType == "express"){
			return "快递";
		}else{
			return "";
		}
	});
	
	//速乐购2.0支付方式
	Handlebars.registerHelper('formatPaymentType', function(paymentType,options) {
		if(paymentType == "shortdatedBalance"){
			return "代金券";
		}else if(paymentType == "balance"){
			return "乐购卡";
		}else{
			return "";
		}
	});
}

// 去除前后空格
String.prototype.trim = function() {
	return this.replace(/(^\s*)|(\s*$)/g, '');
};